import numpy as np
from scipy.integrate import quad


def test_sufficient_conditions():
    """
    验证函数可积的充分条件
    """
    print("=" * 60)
    print("验证函数可积的充分条件")
    print("=" * 60)
    
    # 1. 连续函数示例
    def continuous_func(x):
        return np.sin(x) + np.cos(x)
    
    # 2. 单调函数示例
    def monotonic_func(x):
        return x**3  # 在任意区间上单调递增
    
    # 3. 有有限个间断点的有界函数示例
    def piecewise_func(x):
        # 在x=0.5处有跳跃间断点
        return np.where(x < 0.5, x**2, 2*x - 0.25)
    
    functions = [
        ("连续函数: sin(x)+cos(x)", continuous_func, "定理2: 连续⇒可积"),
        ("单调函数: x³", monotonic_func, "定理3: 单调⇒可积"), 
        ("分段函数(有限间断点)", piecewise_func, "定理4: 有界+有限间断点⇒可积")
    ]
    
    a, b = 0, 1
    
    for name, func, theorem in functions:
        try:
            result, error = quad(func, a, b)
            print(f"{name}")
            print(f"定理: {theorem}")
            print(f"积分结果: ∫₀¹ f(x)dx = {result:.6f}")
            print(f"计算成功: ✓ 可积\n")
        except Exception as e:
            print(f"{name}")
            print(f"定理: {theorem}") 
            print(f"积分错误: {e}")
            print(f"计算失败: ✗ 可能不可积\n")
    
    # 狄利克雷函数的数值模拟（有界但不可积的演示）
    print("狄利克雷函数数值模拟（有界但不可积）:")
    print("由于计算机的离散性，数值计算会得到错误结果")
    
    def dirichlet_approx(x, rational_density=0.5):
        """近似狄利克雷函数：以一定概率返回1，否则返回0"""
        return np.where(np.random.random(len(x)) < rational_density, 1, 0)
    
    x_test = np.linspace(0, 1, 1000)
    # 多次测试显示结果不稳定
    trials = 5
    results = []
    for i in range(trials):
        y_test = dirichlet_approx(x_test, 0.3)  # 30%的有理数密度
        integral_approx = np.trapezoid(y_test, x_test)
        results.append(integral_approx)
    
    print(f"5次测试结果: {results}")
    print("结果不稳定，说明函数不可积")

test_sufficient_conditions()